﻿#include "itemadd.h"
#include "ui_itemadd.h"

ItemAdd::ItemAdd(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ItemAdd)
{
    ui->setupUi(this);

    ui->type->addItems(QStringList() << T_CONE << T_CUBE << T_ITEM << T_BIGCONE << T_BIGCUBE << T_BIGITEM );
    ui->type->setCurrentIndex(-1);
    ui->table->setEnabled(false);
}

ItemAdd::~ItemAdd()
{
    delete ui;
}

bool ItemAdd::addItem(const QString &type,
                      const QString &entry,
                      const QString &title,
                      const QString &category,
                      const QString &label,
                      const QString &detail,
                      const QString &addition,
                      const QString &table)
{
    QSqlQuery query;
    QString sql=QString("insert into %1 "
                        "(type,entry,title,category_t,label_t,detail_t,addition_t,_table) "
                        "values (?,?,?,?,?,?,?,?)")
            .arg(TD_META);

    query.prepare(sql);
    query.addBindValue(type);
    query.addBindValue(entry);
    query.addBindValue(title);
    query.addBindValue(category);
    query.addBindValue(label);
    query.addBindValue(detail);
    query.addBindValue(addition);
    query.addBindValue(table);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void ItemAdd::on_btn_submit_clicked()
{
    if(ui->type->currentIndex() == -1)
    {
        QMessageBox::warning(this,QStringLiteral("类型缺失"),
                             QStringLiteral("必须选择应用类型！"));
        return;
    }

    QString type=ui->type->currentText();
    QString entry=ui->entry->text().trimmed();
    if(entry.isEmpty())
        return;

    QString title=ui->title->text().trimmed();
    if(title.isEmpty())
        return;

    QString category{};
    if(ui->category->isVisible())
    {
        category=ui->category->text().trimmed();
        if(category.isEmpty())
            return;
    }

    QString label=ui->label->text().trimmed();
    if(label.isEmpty())
        return;

    QString detail=ui->detail->text().trimmed();
    if(type != T_CONE && type != T_CUBE)
    {
        if(detail.isEmpty())
            return;
    }

    QString addition=ui->addition->text().trimmed();

    QString table="";
    if(ui->table->isEnabled())
        table=ui->table->text().trimmed();

    if(addItem(type,entry,title,category,label,detail,addition,table))
        accept();
    else
        QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法提交数据！"));
}

void ItemAdd::on_type_currentTextChanged(const QString &text)
{
    if(text == T_ITEM || text == T_BIGITEM)
        ui->category->setVisible(true);
    else
        ui->category->setVisible(false);
}

void ItemAdd::on_externalTable_stateChanged(int state)
{
    if(state == Qt::Checked)
        ui->table->setEnabled(true);
    else
        ui->table->setEnabled(false);
}
